<?php
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 5.1.6 or newer
 *
 * @package		CodeIgniter
 * @author		ExpressionEngine Dev Team
 * @copyright	Copyright (c) 2006 - 2011, EllisLab, Inc.
 * @license		http://codeigniter.com/user_guide/license.html
 * @link		http://codeigniter.com
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * Shopping Cart Class
 *
 * @package		CodeIgniter
 * @subpackage	Libraries
 * @category	Shopping Cart
 * @author		ExpressionEngine Dev Team
 * @link		http://codeigniter.com/user_guide/libraries/cart.html
 */
class Cart {

	// 对产品ID和产品名称进行正则验证属性
	var $product_id_rules	= '\.a-z0-9_-'; // alpha-numeric, dashes, underscores, or periods
	var $product_name_rules	= '\.\:\-_ a-z0-9\[\]\+'; // alpha-numeric, dashes, underscores, colons or periods

	// 私有变量
	var $_cart_contents	= array();
	

	public function init() {}

	/**
	 * 构造方法
	 *
	 */
	public function __construct($params = array())
	{
		// Are any config settings being passed manually?  If so, set them
		$config = array();
		if (count($params) > 0)
		{
			foreach ($params as $key => $val)
			{
				$config[$key] = $val;
			}
		}

		// Grab the shopping cart array from the session table, if it exists
		if (Yii::app()->session->get('cart_contents') !== null)
		{
			$this->_cart_contents = Yii::app()->session->get('cart_contents');
		}
		else
		{
			// 没有购物车时 初始化数据
			$this->_cart_contents['cart_total']  = 0;  //购物车总价
			$this->_cart_contents['total_items'] = 0; //购物车总件数
			$this->_cart_contents['company']  = array(); 
		}

	}

	// --------------------------------------------------------------------

	/**
	 * Insert items into the cart and save it to the session table
	 * 添加到购物车
	 * @access	public
	 * @param	array
	 * @return	bool
	 */
	function insert($items = array())
	{
		// Was any cart data passed? No? Bah...
		if ( ! is_array($items) OR count($items) == 0)
		{
			log_message('error', 'The insert method must be passed an array containing data.');
			return FALSE;
		}

		// You can either insert a single product using a one-dimensional array,
		// or multiple products using a multi-dimensional one. The way we
		// determine the array type is by looking for a required array key named "id"
		// at the top level. If it's not found, we will assume it's a multi-dimensional array.
		// 可以添加一个商品（一维数组），也可以添加多个商品（二维数组）

		$save_cart = FALSE;
		if (isset($items['id']))
		{
			if ($this->_insert($items) == TRUE)
			{
				$save_cart = TRUE;
			}
		}
		else
		{
			foreach ($items as $val)
			{
				if (is_array($val) AND isset($val['id']))
				{
					if ($this->_insert($val) == TRUE)
					{
						$save_cart = TRUE;
					}
				}
			}
		}

		// Save the cart data if the insert was successful
		if ($save_cart == TRUE)
		{
			$this->_save_cart();
			return TRUE;
		}

		return FALSE;
	}

	// --------------------------------------------------------------------

	/**
	 * Insert
	 * 处理插入购物车数据
	 * @access	private
	 * @param	array
	 * @return	bool
	 */
	function _insert($items = array())
	{
		// Was any cart data passed? No? Bah...
		if ( ! is_array($items) OR count($items) == 0)
		{
			log_message('error', 'The insert method must be passed an array containing data.');
			return FALSE;
		}

		// --------------------------------------------------------------------

		/* 前四个数组索引 (id, qty, price 和name) 是 必需的。
		   如果缺少其中的任何一个，数据将不会被保存到购物车中。
		   第5个索引 (options) 是可选的。当你的商品包含一些相关的选项信息时，你就可以使用它。
		   请使用一个数组来保存选项信息。注意：$data['price'] 的值必须大于0 
		   如：$data = array(
               'id'      => 'sku_123ABC',
               'qty'     => 1,
               'price'   => 39.95,
               'name'    => 'T-Shirt',
               'options' => array('Size' => 'L', 'Color' => 'Red')
            );
		*/

		// Does the $items array contain an id, quantity, price, and name?  These are required
		if ( ! isset($items['id']) OR ! isset($items['qty']) OR ! isset($items['price']) OR ! isset($items['name']))
		{
			log_message('error', 'The cart array must contain a product ID, quantity, price, and name.');
			return FALSE;
		}

		// --------------------------------------------------------------------
		// 数量验证，不是数字替换为空
		// Prep the quantity. It can only be a number.  Duh...
		$items['qty'] = trim(preg_replace('/([^0-9])/i', '', $items['qty']));
		// Trim any leading zeros
		$items['qty'] = trim(preg_replace('/(^[0]+)/i', '', $items['qty']));
		// 数量必须是数字或不为0
		// If the quantity is zero or blank there's nothing for us to do
		if ( ! is_numeric($items['qty']) OR $items['qty'] == 0)
		{
			return FALSE;
		}

		// --------------------------------------------------------------------
		// 产品ID验证
		// Validate the product ID. It can only be alpha-numeric, dashes, underscores or periods
		// Not totally sure we should impose this rule, but it seems prudent to standardize IDs.
		// Note: These can be user-specified by setting the $this->product_id_rules variable.
		if ( ! preg_match("/^[".$this->product_id_rules."]+$/i", $items['id']))
		{
			log_message('error', 'Invalid product ID.  The product ID can only contain alpha-numeric characters, dashes, and underscores');
			return FALSE;
		}

		// --------------------------------------------------------------------
		// 验证产品名称，考虑到汉字，暂不使用
		// Validate the product name. It can only be alpha-numeric, dashes, underscores, colons or periods.
		// Note: These can be user-specified by setting the $this->product_name_rules variable.
		/*if ( ! preg_match("/^[".$this->product_name_rules."]+$/i", $items['name']))
		{
			log_message('error', 'An invalid name was submitted as the product name: '.$items['name'].' The name can only contain alpha-numeric characters, dashes, underscores, colons, and spaces');
			return FALSE;
		}*/

		// --------------------------------------------------------------------
		// 价格验证
		// Prep the price.  Remove anything that isn't a number or decimal point.
		$items['price'] = trim(preg_replace('/([^0-9\.])/i', '', $items['price']));
		// Trim any leading zeros
		$items['price'] = trim(preg_replace('/(^[0]+)/i', '', $items['price']));

		// Is the price a valid number?
		if ( ! is_numeric($items['price']))
		{
			log_message('error', 'An invalid price was submitted for product ID: '.$items['id']);
			return FALSE;
		}

		// --------------------------------------------------------------------
		// 属性验证，如果属性存在，属性值+产品ID进行加密保存在$rowid中
		// We now need to create a unique identifier for the item being inserted into the cart.
		// Every time something is added to the cart it is stored in the master cart array.
		// Each row in the cart array, however, must have a unique index that identifies not only
		// a particular product, but makes it possible to store identical products with different options.
		// For example, what if someone buys two identical t-shirts (same product ID), but in
		// different sizes?  The product ID (and other attributes, like the name) will be identical for
		// both sizes because it's the same shirt. The only difference will be the size.
		// Internally, we need to treat identical submissions, but with different options, as a unique product.
		// Our solution is to convert the options array to a string and MD5 it along with the product ID.
		// This becomes the unique "row ID"
		if(isset($items['package'])){
			if (isset($items['options']) AND count($items['options']) > 0)
			{
				$rowid = md5($items['id'].implode(',', $items['options']).$items['packagesid']);
			}
			else
			{	
				// 没有属性时直接对产品ID加密
				// No options were submitted so we simply MD5 the product ID.
				// Technically, we don't need to MD5 the ID in this case, but it makes
				// sense to standardize the format of array indexes for both conditions
				$rowid = md5($items['id'].$items['packagesid']);
			}
		}else{
			if (isset($items['options']) AND count($items['options']) > 0)
			{
				$rowid = md5($items['id'].implode(',', $items['options']));
			}
			else
			{	
				// 没有属性时直接对产品ID加密
				// No options were submitted so we simply MD5 the product ID.
				// Technically, we don't need to MD5 the ID in this case, but it makes
				// sense to standardize the format of array indexes for both conditions
				$rowid = md5($items['id']);
			}
		}

		// --------------------------------------------------------------------
		// 检测购物车中是否有该产品，如果有，在原来的基础上加上本次新增的商品数量
		$_contents = $this->_cart_contents;
		$_tmp_contents = array();
		if (count($_contents)) {
			foreach ($_contents as $val)
			{
				if (is_array($val) AND isset($val['rowid']) AND isset($val['qty']) AND $val['rowid']==$rowid)
				{
					$_tmp_contents[$val['rowid']]['qty'] = $val['qty'];
				} else {
					$_tmp_contents[$val['rowid']]['qty'] = 0;
				}
			}
		}

		// Now that we have our unique "row ID", we'll add our cart items to the master array
		// 清除原来的数据
		// let's unset this first, just to make sure our index contains only the data from this submission
		unset($this->_cart_contents[$rowid]);

		// 清除原来的数据
		// Create a new index with our new row ID
		$this->_cart_contents[$rowid]['rowid'] = $rowid;

		// 添加新项目
		// And add the new items to the cart array
		foreach ($items as $key => $val)
		{
			if ($key=='qty' && isset($_tmp_contents[$rowid][$key])) {
				$this->_cart_contents[$rowid][$key] = $val+$_tmp_contents[$rowid][$key];
			} else {
				$this->_cart_contents[$rowid][$key] = $val;
			}
		}

		// Woot!
		return TRUE;
	}

	// --------------------------------------------------------------------

	/**
	 * Update the cart
	 *	更新购物车
	 * This function permits the quantity of a given item to be changed.
	 * Typically it is called from the "view cart" page if a user makes
	 * changes to the quantity before checkout. That array must contain the
	 * product ID and quantity for each item.
	 *
	 * @access	public
	 * @param	array
	 * @param	string
	 * @return	bool
	 */
	function update($items = array())
	{
		// 验证
		// Was any cart data passed?
		if ( ! is_array($items) OR count($items) == 0)
		{
			return FALSE;
		}

		// You can either update a single product using a one-dimensional array,
		// or multiple products using a multi-dimensional one.  The way we
		// determine the array type is by looking for a required array key named "id".
		// If it's not found we assume it's a multi-dimensional array
		$save_cart = FALSE;
		if (isset($items['rowid']) AND isset($items['qty']))
		{
			if ($this->_update($items) == TRUE)
			{
				$save_cart = TRUE;
			}
		}
		else
		{
			foreach ($items as $val)
			{
				if (is_array($val) AND isset($val['rowid']) AND isset($val['qty']))
				{
					if ($this->_update($val) == TRUE)
					{
						$save_cart = TRUE;
					}
				}
			}
		}

		// Save the cart data if the insert was successful
		if ($save_cart == TRUE)
		{
			$this->_save_cart();
			return TRUE;
		}

		return FALSE;
	}

	// --------------------------------------------------------------------

	/**
	 * Update the cart
	 * 处理更新购物车
	 * This function permits the quantity of a given item to be changed.
	 * Typically it is called from the "view cart" page if a user makes
	 * changes to the quantity before checkout. That array must contain the
	 * product ID and quantity for each item.
	 *
	 * @access	private
	 * @param	array
	 * @return	bool
	 */
	function _update($items = array())
	{
		// Without these array indexes there is nothing we can do
		if ( ! isset($items['qty']) OR ! isset($items['rowid']) OR ! isset($this->_cart_contents[$items['rowid']]))
		{
			return FALSE;
		}
		// 检测数量
		// Prep the quantity
		$items['qty'] = preg_replace('/([^0-9])/i', '', $items['qty']);

		// Is the quantity a number?
		if ( ! is_numeric($items['qty']))
		{
			return FALSE;
		}

		// Is the new quantity different than what is already saved in the cart?
		// If it's the same there's nothing to do
		if ($this->_cart_contents[$items['rowid']]['qty'] == $items['qty'])
		{
			return FALSE;
		}

		// Is the quantity zero?  If so we will remove the item from the cart.
		// If the quantity is greater than zero we are updating
		if ($items['qty'] == 0)
		{
			unset($this->_cart_contents[$items['rowid']]);
		}
		else
		{
			$this->_cart_contents[$items['rowid']]['qty'] = $items['qty'];
		}

		return TRUE;
	}

	// --------------------------------------------------------------------

	/**
	 * Save the cart array to the session DB
	 * 保存购物车到Session里
	 * @access	private
	 * @return	bool
	 */
	function _save_cart()
	{
		// Unset these so our total can be calculated correctly below
		unset($this->_cart_contents['total_items']);
		unset($this->_cart_contents['cart_total']);

		// Lets add up the individual prices and set the cart sub-total
		$total = 0;     //总金额		
		foreach ($this->_cart_contents as $key => $val)
		{
			// We make sure the array contains the proper indexes
			if ( ! is_array($val) OR ! isset($val['price']) OR ! isset($val['qty']))
			{
				continue;
			}

			$total += ($val['price'] * $val['qty']); 		

			$this->_cart_contents['company'][] = $val['zm_id'];

			// Set the subtotal  单品小计
			$this->_cart_contents[$key]['subtotal'] = ($this->_cart_contents[$key]['price'] * $this->_cart_contents[$key]['qty']); 
		}
		
		// Set the cart total and total items.
		$total_items = $this->_cart_contents;
		unset($total_items['company']);
		$this->_cart_contents['total_items'] = count($total_items);
		$this->_cart_contents['cart_total'] = $total;

		// Is our cart empty?  If so we delete it from the session
		if (count($this->_cart_contents) <= 2)
		{
			Yii::app()->session->remove('cart_contents');

			// Nothing more to do... coffee time!
			return FALSE;
		}

		// If we made it this far it means that our cart has data.
		// Let's pass it to the Session class so it can be stored
		Yii::app()->session->add('cart_contents', $this->_cart_contents);

		// Woot!
		return TRUE;
	}

	// --------------------------------------------------------------------

	/**
	 * Cart Total
	 * 购物车中的总计金额
	 * @access	public
	 * @return	integer
	 */
	function total()
	{
		return $this->_cart_contents['cart_total'];
	}

	// --------------------------------------------------------------------

	/**
	 * Total Items
	 * 购物车中总共的项目数量
	 * Returns the total item count
	 *
	 * @access	public
	 * @return	integer
	 */
	function total_items()
	{	

		return $this->_cart_contents['total_items'];
	}

	/**
	 * Company
	 * 购物车中运费模板种类
	 * Returns the total item count
	 *
	 * @access	public
	 * @return	array
	 */
	function total_postage() 
	{
		foreach ($this->_cart_contents as $key => $val)
		{
			if($val['exp_status']==2){
			$this->_cart_contents['postage'][] = $val['ze_id'];
			}
		}
		//清除空值
		$this->_cart_contents['postage'] = array_filter($this->_cart_contents['postage']);
		return array_unique($this->_cart_contents['postage']);
	}

	/**
	 * 
	 * 购物车中是否有活动产品
	 *
	 * @access	public
	 * @return	array
	 */
	function activity_pro() 
	{	
		$return = 0;
		foreach ($this->_cart_contents as $key => $val)
		{
			if( $val['active'] != 0 ){
				$return = 1;
			}
		}			
		return $return;
	}

	/**
	 * Company
	 * 购物车中有运费的产品ID
	 * Returns the total item count
	 *
	 * @access	public
	 * @return	array
	 */
	function total_postage_pro() 
	{
		$this->_cart_contents['postage']= array();
		foreach ($this->_cart_contents as $key => $val)
		{
			if( $val['exp_status'] == 2 ){
			$this->_cart_contents['postage'][] = $val['ze_id'];
			}
		}
		//清除空值
		$postage = array_unique(array_filter($this->_cart_contents['postage']));

		foreach ($this->_cart_contents as $key => $val)
		{
			if($val['exp_status']==2){
				foreach ($postage as $k => $v) {
					if($v == $val['ze_id'] ){
						if($val['weight']){
							$producids[$v]['qty'] += $val['qty'];
							$producids[$v]['weight'] += (ceil($val['weight']/500))*$val['qty'];
						}else{
							$producids[$v]['qty'] += $val['qty'];
						}
						
					}
				}
			
			}
		}
		
		return $producids;
	}

	/**
	 * Company
	 * 购物车中公司ID集
	 * Returns the total item count
	 *
	 * @access	public
	 * @return	array
	 */
	function company()
	{
		foreach ($this->_cart_contents as $key => $val)
		{
			$this->_cart_contents['company'][] = $val['zm_id'];
		}
		//清除空值
		$this->_cart_contents['company'] = array_filter($this->_cart_contents['company']);
		return array_unique($this->_cart_contents['company']);
	}

	// --------------------------------------------------------------------

	/**
	 * Cart Contents
	 * 返回一个包含了购物车中所有信息的数组
	 * Returns the entire cart array
	 *
	 * @access	public
	 * @return	array
	 */
	function contents()
	{
		$cart = $this->_cart_contents;

		// Remove these so they don't create a problem when showing the cart table
		unset($cart['total_items']);
		unset($cart['cart_total']);
		unset($cart['company']);
		unset($cart['postage']);

		return $cart;
	}

	/**
	 * Cart Contents
	 * 返回一个包含了公司与购物车中所有信息的数组
	 * Returns the entire cart array
	 *
	 * @access	public
	 * @return	array
	 */
	function com_contents()
	{
		$cart = $this->_cart_contents;

		unset($cart['total_items']);
		unset($cart['cart_total']);
		unset($cart['company']);
		unset($cart['postage']);
		// Remove these so they don't create a problem when showing the cart table
		//$this->_cart_contents['company'] = '';
		//统计公司
		
		foreach ($this->_cart_contents as $key => $val)
		{
			$this->_cart_contents['company'][] = $val['zm_id'];
		}

		//清除空值
		$this->_cart_contents['company'] = array_unique(array_filter($this->_cart_contents['company']));
		
		foreach ($this->_cart_contents as $key => $val)
		{	
			if($val['exp_status']==2){
				$expids[] = $val['ze_id'];
			}
		}
		//清除空值与去重复
		if(is_array($expids)){
			$expids = array_unique(array_filter($expids));
		}else{
			$expids = '';
		}
		///print_r($expids);
		foreach ($this->_cart_contents['company'] as $key => $val) {
			
			foreach ($cart as $k=>$c) {
			//判断是属于那个公司				
				if($val == $c['zm_id']){
					//判断是否免邮
					if( $c['exp_status'] == 1 ){
						$comcart[$val]['franking'][$k] = $c; //免邮
					}else{
						foreach ($expids as $expkey => $expval) 
						{	//判断运费模板
							if( $expval == $c['ze_id']){
							$comcart[$val]['postage'][$expval][$k] = $c;  //运费模板	
							}							
						}
						
					}
				}				
			}			

		}
		
		//print_r($comcart);

		return $comcart;
	}

	// --------------------------------------------------------------------

	/**
	 * Has options
	 * 购物车中是否有特定的列包含选项信息
	 * Returns TRUE if the rowid passed to this function correlates to an item
	 * that has options associated with it.
	 * 如果购物车中特定的列包含选项信息，本函数会返回 TRUE(布尔值)，本函数被设计为与 contents() 一起在循环中使用
	 * @access	public
	 * @return	array
	 */
	function has_options($rowid = '')
	{
		if ( ! isset($this->_cart_contents[$rowid]['options']) OR count($this->_cart_contents[$rowid]['options']) === 0)
		{
			return FALSE;
		}

		return TRUE;
	}

	// --------------------------------------------------------------------

	/**
	 * Product options
	 * 以数组的形式返回特定商品的选项信息
	 * Returns the an array of options, for a particular product row ID
	 * 本函数被设计为与 contents() 一起在循环中使用
	 * @access	public
	 * @return	array
	 */
	function product_options($rowid = '')
	{
		if ( ! isset($this->_cart_contents[$rowid]['options']))
		{
			return array();
		}

		return $this->_cart_contents[$rowid]['options'];
	}

	// --------------------------------------------------------------------

	/**
	 * Format Number
	 * 格式化数值
	 * Returns the supplied number with commas and a decimal point.
	 * 返回格式化后带小数点的值（小数点后有2位），一般价格使用
	 * @access	public
	 * @return	integer
	 */
	function format_number($n = '')
	{
		if ($n == '')
		{
			return '';
		}

		// Remove anything that isn't a number or decimal point.
		$n = trim(preg_replace('/([^0-9\.])/i', '', $n));

		return number_format($n, 2, '.', ',');
	}

	// --------------------------------------------------------------------

	/**
	 * Destroy the cart
	 * 销毁购物车
	 * Empties the cart and kills the session
	 * 这个函数一般是在处理完用户订单后调用
	 * @access	public
	 * @return	null
	 */
	function destroy()
	{
		unset($this->_cart_contents);

		$this->_cart_contents['cart_total'] = 0;
		$this->_cart_contents['total_items'] = 0;

		Yii::app()->session->remove('cart_contents');
	}



}
// END Cart Class

/* End of file Cart.php */
/* Location: ./system/libraries/Cart.php */

function log_message($a, $b)
{
	var_dump($a, $b);
}
